package com.leyou.gateway.filters;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import java.util.List;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.*;


@Slf4j
@Component
public class AuthFilter extends ZuulFilter {


    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private FilterProperties filterProp;

    /**
     * 过滤器类型：pre、route、post、error
     * @return
     */
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    @Override
    public boolean shouldFilter() {
        //获取上下文
        RequestContext context = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = context.getRequest();
        //获取请求路径
        String path = request.getRequestURI();
        //判断路径是否是可放行的路径
        boolean isAllow = isAllowPath(path);
        // 是否执行run中的拦截逻辑，如果一个路径要放行，返回false
        return !isAllow;
    }

    private boolean isAllowPath(String path) {
        // 遍历允许访问的路径
        List<String> allowPaths = filterProp.getAllowPaths();
        for (String allowPath : allowPaths) {
            // 然后判断是否是符合
            if (path.startsWith(allowPath)){
                return true;
            }
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        //获取上下文
        RequestContext context = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = context.getRequest();
        //获取token
        String token = CookieUtils.getCookieValue(request, jwtProp.getUser().getCookieName());
        try {
            //解析token
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
            //获取用户
            UserInfo userInfo = payload.getUserInfo();
            String role = userInfo.getRole();
            //把用户信息放到请求头中
            context.addZuulRequestHeader(jwtProp.getUser().getHeaderName(),userInfo.getId().toString());
            //获取当前资源路径
            String path = request.getRequestURI();
            String method = request.getMethod();
            //TODO 判断权限，此处暂时空置，等待权限服务完成后补充
            log.info("【网关】用户{},角色{}。访问服务{} : {}，", userInfo.getUsername(), role, method,path);
        } catch (Exception e) {
            //解析token异常，说明未登录，拦截请求
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(401);
        }
        return null;
    }
}
